import {
    Broadcast,
    BroadcastRequest,
    BroadcastResponse,
    BroadcastResponseStatus,
    Controller
} from "./model/ControllerOpt";
import {Logger} from "../frame/apiModel/config/Logger";

export class ControllerBroadcast implements Broadcast {
    private static controllerCentre: ControllerBroadcast = new ControllerBroadcast();
    private controllers: Controller[] = [];
    static getInstance() {
        return ControllerBroadcast.controllerCentre;
    }
    init() {
    }
    startListen(controller: Controller) {
        const no = controller.getControllerNo();
        ControllerBroadcast.getInstance().controllers[no] = controller;
    }

    broadcast(request: BroadcastRequest): BroadcastResponse {
        const no = request.controllerNo;
        const type = request.broadcastType;
        const controller = ControllerBroadcast.getInstance().controllers[no];
        if (controller) {
            const ret = controller.notify(request);
            if (ret.status === BroadcastResponseStatus.failed) {
                Logger.toastError(`对应控制器没有提供对当前动作的响应行为，请检查代码(控制器序号${no}, 广播类型${request.broadcastType})`);
            }
            return ret;
        } else {
            Logger.toastError(`对应控制器(${no})可能还没注册，无法处理(${type})，请检查是否注册对应控制器`);
        }
        const ret: BroadcastResponse = { controllerNo: 0, data: {}, status: BroadcastResponseStatus.none };
        return ret;
    }
}